<?php

namespace app\api\model;

use think\Model;

class Product extends BaseModel
{
   protected $hidden = ['category_id','img_id','pivot','create_time','update_time','delete_time'];

    //    读取器
    public function getMainImgUrlAttr($value,$data){
        return $this->prefixImage($value,$data);
    }

    public function imgs(){
        return $this->hasMany('ProductImage','product_id','id');
    }

    public function properties(){
        return $this->hasMany('ProductProperty','product_id','id');
    }

    public static function getMostRecent($count)
    {
        $products = self::limit($count)
            ->order('create_time desc')
            ->select();
        return $products;
    }

    public static function getProductsByCategoryId($catecoryId){
        $products = self::where(['category_id'=>$catecoryId])
            ->select();
        return $products;
    }

    /*
     * @商品详情
     * */
    public static function getProductDetail($id)
    {
        /*return self::with(['imgs.imgUrl','properties'])
        ->find($id);*/

        /*
         * 闭包查询
         * */
        return self::with([
            /*$query代表查询后的对象*/
            'imgs'=>function($query){
                $query->with(['imgUrl'])
                    ->order('order','asc');
            }
        ])
            ->with(['properties'])
            ->find($id);
    }
}
